package com.hulk.rpc.transport.server.rpc.handler;

import com.hulk.rpc.config.common.HulkConstants;
import com.hulk.rpc.filter.RpcServerFilter;
import com.hulk.rpc.invoke.ServiceInvokeFactory;
import com.hulk.rpc.serialize.Serializer;
import com.hulk.rpc.transport.server.rpc.codec.RequestDecoder;
import com.hulk.rpc.transport.server.rpc.codec.ResponseEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

import java.util.concurrent.CopyOnWriteArrayList;

public class NettyRpcChannelInitializer extends ChannelInitializer<SocketChannel> {

  private final ServiceInvokeFactory invokerFactory;
  private final Serializer serializer;
  private final CopyOnWriteArrayList<RpcServerFilter> filters;

  public NettyRpcChannelInitializer(ServiceInvokeFactory invokerFactory, Serializer serializer,
                                    CopyOnWriteArrayList<RpcServerFilter> filters) {
    this.invokerFactory = invokerFactory;
    this.serializer = serializer;
    this.filters = filters;

  }

  @Override
  public void initChannel(SocketChannel ch) throws Exception {
    ch.pipeline()//
            .addLast("encoder", new ResponseEncoder(serializer))//
            .addLast("decoder", new RequestDecoder(HulkConstants.MAX_FRAME_LENGTH, serializer))//
            .addLast("handler", new NettyRpcServerHandler(invokerFactory, filters));
  }
}
